import db from '../models/index'
import jwt = require('jsonwebtoken');
const secret = 'bbsGouLiZhi*@!***';
/** 公共方法 */
export default function () {
    return async (ctx: any, next: any) => {

        /** 成功返回 */
        ctx.success = function (data: string = '') {
            ctx.body({code: 0, msg: 'success', data: data});
            return false;
         };
        /**
         * 错误返回
         * error
         * @param msg
         */
        ctx.errors = function (msg: string = 'error') {
            ctx.body = {code: 1, msg: msg, data: ''};
            return false;
        };
        /** 返回全局模型 */
        ctx.db = db

        /** 全局op */
        ctx.Op = db.Op
        /**
         * token 生产token
         * @param username
         * @param role
         * @param expires
         * @param strTimer
         * @returns {*}
         */
        ctx.createToken = (user: string, id: number, expires: string, strTimer: string) => {
            const token: any = jwt.sign({
                    User: user,
                    role: {role: id}
                }, secret, {
                    expiresIn: expires + ' ' + strTimer
            });
            return token;
        };
        await next();
    }
  }